<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 编辑设备型号
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <Form
        ref="formValidate"
        :model="bloc.model"
        :rules="ruleValidate3"
        :label-width="111"
        style="padding:50px 10% 0 10%;width: 860px"
      >
        <!-- <FormItem label="设备类型" prop="sortId">
          <Input v-model="model.sortId"></Input>
        </FormItem>-->
        <FormItem label="设备分类:" prop="sortId">
          <Select disabled v-model="bloc.model.sortId" filterable style="width: 400px">
            <Option
              v-for="item in bloc.sortList"
              :value="item.id"
              :key="item.id"
            >{{ item.sortName }}
            </Option>
          </Select>
        </FormItem>

        <!--        <FormItem label="设备型号:" prop="modelName">-->
        <!--          <Input v-model="bloc.model.modelName" style="width: 300px"/>-->
        <!--        </FormItem>-->
        <FormItem label="设备型号:" prop="modelName">
          <i-select disabled v-model="bloc.model.modelName" filterable style="width: 400px">
            <i-option
              v-for="(item,index) in bloc.deviceModelName"
              :value="item"
              :key="index"
            >{{ item }}
            </i-option>
          </i-select>
        </FormItem>

        <FormItem label="蓝牙类型:" prop="bletype">
          <Select v-model="bloc.model.bletype" filterable style="width: 400px">
            <Option
              v-for="(item,index) in bloc.bletypeList"
              :value="item.id"
              :key="index"
            >{{ item.title }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="渠道:" prop="channel">
          <Select v-model="bloc.model.channel" filterable style="width: 400px">
            <Option
              v-for="(item,index) in bloc.channelList"
              :value="item.value"
              :key="index"
            >{{ item.title }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="配置:" prop="configure">
          <Select v-model="bloc.model.configure" filterable style="width: 400px">
            <Option
              v-for="item in bloc.configureList"
              :value="item"
              :key="item"
            >{{ item }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="设备图标:" prop="modelIcon">
          <div class="demo-upload-list" v-for="(item, index) in fileList" :key="item.modelIcon">
            <template v-if="item.status === 'finished'">
              <img :src="item.modelIcon">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.modelIcon)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="200"
            :format="['jpg','png']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-success="handleSuccess"
            type="drag"
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="visible">
              <img :src="imgUrl" v-if="visible" style="width: 100%">
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG格式，图片小于200k</p>
        </FormItem>

        <FormItem label="海报:" prop="poster">
          <div class="demo-upload-list" v-for="(item, index) in posterFileList" :key="item.modelIcon">
            <template v-if="item.status === 'finished'">
              <img :src="item.modelIcon">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="posterHandleView(item.modelIcon)"></Icon>
                <Icon type="ios-trash-outline" @click.native="posterHandleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="4000"
            :format="['jpg','png']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError"
            :on-exceeded-size="posterHandleMaxSize1"
            :on-success="posterHandleSuccess"
            type="drag"
            style="display: inline-block;width:58px;margin-left:15px"
          >
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
            <Modal title="View Image" v-model="posterVisible">
              <img :src="posterUrl" v-if="posterVisible" style="width: 100%">
            </Modal>
          </Upload>
          <p style="margin-left: 15px">支持 JPG、PNG格式，图片小于2M</p>
        </FormItem>
        <FormItem label="隐藏设置：" :label-width="120" required>
          <i-switch @on-change="switchStatus"
                    v-model="enable"
          ></i-switch>
        </FormItem>

        <FormItem label="所属品牌商:" prop="companyId">
          <!--          <Select-->
          <!--            v-model="bloc.model.companyId"-->
          <!--            filterable>-->
          <!--            <Option v-for="(item, index) in bloc.companyList" :value="item.companyId" :key="index">-->
          <!--              {{item.companyName}}-->
          <!--            </Option>-->
          <!--          </Select>-->
          <CompanySeletorSingle :companyId="bloc.model.companyId" style="width: 400px"
                                :disable="bloc.model.companyId !==0"
                                @on-change="value=>bloc.model.companyId=value"></CompanySeletorSingle>
        </FormItem>

        <FormItem label="插件管理:" prop="isSoftware" style="display: none">
          <i-switch v-model="bloc.model.isSoftware" size="large" style="margin-left: 20px">
            <span slot="open"></span>
            <span slot="close"></span>
          </i-switch>
        </FormItem>

        <FormItem label="固件管理:" prop="isFirmware" style="display: none">
          <i-switch v-model="bloc.model.isFirmware" size="large" style="margin-left: 20px">
            <span slot="open"></span>
            <span slot="close"></span>
          </i-switch>
        </FormItem>

        <FormItem label="自动模式管理:" prop="isSelfMotion" style="display: none">
          <i-switch v-model="bloc.model.isSelfMotion" size="large" style="margin-left: 20px">
            <span slot="open"></span>
            <span slot="close"></span>
          </i-switch>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <AppButton ref="edit"
                   style="margin-left: 30px;width: 100px;height: 40px;"
                   type="primary"
                   @click="editModel('formValidate')"
        >保存
        </AppButton>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {store} from '@/store/Store';
  import {baseUrl} from '@/base/Request';
  import {Route} from 'vue-router';
  import {FormBloc} from '../../FormBloc';
  import CompanySeletorSingle from '@/component/CompanySeletorSingle.vue';
  import {AppButton} from '@/type/AppButton';

  @Component({
    components: {CompanySeletorSingle}
  })
  export default class extends Vue {
[x: string]: any;
    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        vm.bloc.sortId = Number(vm.$route.query.sortId);
        vm.bloc.getCompanyList(vm.bloc.company.pageIndex, vm.bloc.company.pageSize, 'ASC')
        vm.bloc.getAllSort(1, 1000, 'ASC')
        vm.bloc.putDeviceModelGather()
        vm.bloc.getModel(vm.idx)
          .then(res => {
              vm.bloc.fileList = []
              vm.bloc.fileList.push(vm.bloc.model.modelIcon)
              vm.bloc.posterFileList = []
            if (vm.bloc.model.poster !== '') {
                vm.bloc.posterFileList.push(vm.bloc.model.poster)
            }
          })
      });
    }

    bloc = new FormBloc()

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      }
    };

    get uploadAction() {
      return `${baseUrl}/api/upload/image`
    }

    imgUrl = '';
    posterUrl = '';
    visible = false;
    posterVisible = false;

    get fileList() {
      return this.bloc.fileList.map(x => {
        return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
      });
    }

    get posterFileList() {
      return this.bloc.posterFileList.map(x => {
        return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
      });
    }

    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    }

    posterHandleView(url) {
      this.posterUrl = url;
      this.posterVisible = true;
    }

    handleRemove(file) {
      this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
      this.bloc.model.modelIcon = ''
    }

    posterHandleRemove(file) {
      this.bloc.posterFileList.splice(this.bloc.posterFileList.indexOf(file), 1);
    }

    ruleValidate3: any = {
      companyId: [
        {required: true, message: '品牌商名称不能为空', trigger: 'blur', type: 'number'}
      ],
      // isFirmware: [
      //   {required: true, message: '固件不能为空', trigger: 'change', type: 'boolean'}
      // ],
      // isSelfMotion: [
      //   {required: true, message: '自动模式不能为空', trigger: 'change', type: 'boolean'}
      // ],
      // isSoftware: [
      //   {required: true, message: '插件不能为空', trigger: 'change', type: 'boolean'}
      // ],
      modelIcon: [
        {required: true, message: '设备图标不能为空', trigger: 'change'}
      ],
      poster: [
        {required: true, message: '设备图标不能为空', trigger: 'change'}
      ],
      modelName: [{required: true, message: '型号不能为空', trigger: 'blur'}],
      configure: [{required: true, message: '型号不能为空', trigger: 'blur'}]
      // sortId: [{ required: true, message: "类型名称不能为空", trigger: "change" }]
    };

    get idx() {
      return Number(this.$route.params.id);
    }
      switchStatus(status) {
             if (status) {
              this.bloc.model.isHide = 1
          } else {
              this.bloc.model.isHide = 0
          }
      };
      get enable() {
          return this.bloc.model.isHide === 1;
      }
    // 编辑型号
    editModel(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.$refs.edit.bloc.loading = true;
          this.bloc
            .editModel(this.bloc.model)
            .then(res => {
              this.$Message.success('保存成功');
              this.$router.push({path: '/device', query: {sortId: this.bloc.sortId + ''}});
            })
            .catch(res => {
              this.$Message.error('保存失败');
            })
            .finally(() => {
              this.$refs.edit.bloc.loading = false;
            });
        }
      });
    }

    handleMaxSize(file) {
      // this.$Notice.warning({
      //   title: '超出了文件大小限制',
      //   desc: file.name + ' 文件太大，不能超出2M'
      // });
      this.$Message.error('图片大小不能超过50k')
    }

    posterHandleMaxSize1(file) {
      this.$Message.error('图片大小不能超过2M')
    }

    handleFormatError(file) {
      // this.$Notice.warning({
      //   title: '文件格式不正确',
      //   desc: file.name + '文件格式不正确，请选择格式为 JPG、PNG格式的文件'
      // });
      this.$Message.error('请选择格式为JPG、PNG格式的文件')
    }

    handleSuccess(res, file) {
      this.bloc.model.modelIcon = res.data[0]
      if (this.bloc.fileList.length > 0) {
        this.bloc.fileList = []
      }
      this.bloc.fileList.push(this.bloc.model.modelIcon)
    }

    posterHandleSuccess(res, file) {
      this.bloc.model.poster = res.data[0]
      if (this.bloc.posterFileList.length > 0) {
        this.bloc.posterFileList = []
      }
      this.bloc.posterFileList.push(this.bloc.model.poster)
    }

    handleCancel() {
      this.$router.push({path: '/device', query: {sortId: this.bloc.sortId + ''}});
    }

    $refs!: {
      edit: AppButton
      formValidate: HTMLFormElement;
    };
  }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    display: flex !important;
    justify-content: start !important;
    align-items: center !important;
  }
</style>
